#include <iostream>
#include <string>
#include <cstring>
#include <unordered_map>
#define VNAME(name) (#name)
#define debug(x) {std::cout << " (" << VNAME(x) << ": " << (x) << ") ";}


using namespace std;
const int N = 1e5 + 5;
unordered_map<int, int> M;
unordered_map<int, int> P;
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
    int n;
    cin >> n;
    while (n --) {
        string s;
        int res = 0;
        int X = 0, Y = 0;
        M.clear();
        P.clear();
        cin >> s;
        for (auto i : s) {
            if (i == 'A') X ++;
            else Y ++;
            if (X == Y) res = X;
            else if (P[X - Y]) {
                res = max(res, Y - M[X - Y]);
            }
            if (!P[X - Y]) M[X - Y] = Y;
            P[X - Y] = true;
        }
        cout << res * 2 << endl;
    }
    system("pause");
    return 0;
}